package com.friend.joey.applicationfriend.ChildActivities;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.friend.joey.applicationfriend.Adapters.RememAdapter;
import com.friend.joey.applicationfriend.AlarmService;
import com.friend.joey.applicationfriend.Classes.RememRecord;
import com.friend.joey.applicationfriend.Classes.TimeDeal;
import com.friend.joey.applicationfriend.Database.MyDatabaseHelper;
import com.friend.joey.applicationfriend.R;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Joey on 2017/5/31.
 */

public class ChildForgetActivity extends AppCompatActivity {
    private List<RememRecord> remList = new ArrayList<>();//备忘消息
    private RememAdapter adapter;
    private RecyclerView remRecyclerView;
    private Button button_new;
    //闹钟相关
    private AlarmManager manager;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.child_forget);
        remRecyclerView=(RecyclerView)findViewById(R.id.crem_recycler_view);
        button_new = (Button)findViewById(R.id.button_cfnew);

        initRems();
        LinearLayoutManager layoutManager = new LinearLayoutManager(ChildForgetActivity.this);
        remRecyclerView.setLayoutManager(layoutManager);
        adapter = new RememAdapter(remList);
        adapter.setOnRemCallbackListener(new RememAdapter.onRemCallback(){
            @Override
            public void onDeleteclick(int itempostion) {
                //Toast.makeText(mactivity,String.valueOf(itempostion),Toast.LENGTH_SHORT).show();
                deleteFromDatabase(remList.get(itempostion));
                remList.remove(itempostion);
                adapter.notifyItemRemoved(itempostion);
                adapter.notifyItemRangeChanged(itempostion,remList.size()-itempostion);
                //remRecyclerView.scrollToPosition(remList.size()-1);//定位到最后一行
            }

            @Override
            public void onShowclick() {

            }
        });
        remRecyclerView.setAdapter(adapter);
        button_new.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.FFNEW");
                startActivityForResult(intent,1);
            }
        });

        //闹钟相关
        manager=(AlarmManager)getSystemService(ALARM_SERVICE);
    }

    //初始化备忘录列表
    private void initRems(){
        RememRecord rem0;
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(ChildForgetActivity.this,"TestTalk.db",null,2);//数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("forget",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            while(cursor.moveToNext())
            {
                String title= cursor.getString(cursor.getColumnIndex("title"));
                String content=cursor.getString(cursor.getColumnIndex("content"));
                String addtime=cursor.getString(cursor.getColumnIndex("addtime"));
                int dataType=cursor.getInt(cursor.getColumnIndex("type"));
                int id=cursor.getInt(cursor.getColumnIndex("id"));
                if(dataType==RememRecord.NOT_ALERT){
                    rem0=new RememRecord(id,title,content,addtime,dataType);
                    remList.add(rem0);
                }else if(dataType==RememRecord.SET_ALERT){
                    String alerttime=cursor.getString(cursor.getColumnIndex("alerttime"));
                    int alertid=cursor.getInt(cursor.getColumnIndex("addid"));
                    rem0=new RememRecord(id,title,content,addtime,dataType,alerttime,alertid);
                    remList.add(rem0);
                }
            }
        }
        else{
            RememRecord rem1=new RememRecord("吃药","止咳糖浆",RememRecord.NOT_ALERT);
            remList.add(rem1);
            RememRecord rem2=new RememRecord("看电视","京剧大赏",RememRecord.NOT_ALERT);
            remList.add(rem2);
            RememRecord rem3=new RememRecord("吃药3","止咳糖浆3",RememRecord.NOT_ALERT);
            remList.add(rem3);
            Toast.makeText(ChildForgetActivity.this, "数据库未获取到信息", Toast.LENGTH_SHORT).show();
        }
    }
    private void deleteFromDatabase(RememRecord rem){
        //String s=rem.getTitle()+rem.getContent()+Integer.toString(rem.getId());
        //Toast.makeText(ChildForgetActivity.this, "删除"+s, Toast.LENGTH_SHORT).show();
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(ChildForgetActivity.this,"TestTalk.db",null,2);//数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int id=rem.getId();
        db.delete("forget","id=?",new String[]{Integer.toString(id)});
        db.close();
    }
    private void insertIntoDatabase(RememRecord rem){
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(ChildForgetActivity.this,"TestTalk.db",null,2);//数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title",rem.getTitle());
        values.put("content",rem.getContent());
        values.put("addtime",rem.getAddtime());
        values.put("id",rem.getId());
        int type=rem.getType();
        values.put("type",type);
        if(type==RememRecord.SET_ALERT) {
            values.put("alerttime", rem.getAlerttime());
            values.put("addid", rem.getalertId());
        }
        long i=db.insert("forget",null,values);
        //Toast.makeText(MainActivity.this,"添加备忘"+Long.toString(i), Toast.LENGTH_SHORT).show();
        db.close();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Boolean add=data.getExtras().getBoolean("add");
        if(add) {
            String rtitle = data.getStringExtra("title");
            //Toast.makeText(this,rtitle,Toast.LENGTH_SHORT).show();
            String rcontent = data.getExtras().getString("content");
            Boolean isChecked=data.getExtras().getBoolean("isChecked");
            RememRecord rem1;
            if(isChecked){
                TimeDeal setTime=new TimeDeal(data.getIntExtra("year",0),
                        data.getIntExtra("month",0),
                        data.getIntExtra("day",0),
                        data.getIntExtra("hour",0),
                        data.getIntExtra("min",0));
                int alertId=(int)data.getExtras().getLong("alertid");
                //RememRecord rem1=new RememRecord(0,rtitle,rcontent,RememRecord.SET_ALERT);
                rem1=new RememRecord(rtitle,rcontent,setTime,alertId);
                remList.add(rem1);
                //添加闹钟
                addAlet(data.getExtras().getLong("alertid"),rtitle,rcontent);
            }else{
                rem1=new RememRecord(rtitle,rcontent,RememRecord.NOT_ALERT);
                remList.add(rem1);
            }
            insertIntoDatabase(rem1);
            adapter.notifyItemChanged(remList.size()-1);//有新消息时刷新显示
        }

    }

    public void addAlet(long time,String title,String content){
        Toast.makeText(ChildForgetActivity.this,"添加闹钟",Toast.LENGTH_SHORT).show();
        Intent i = new Intent(ChildForgetActivity.this,AlarmService.class);
        i.putExtra("time",(int)time);
        i.putExtra("title",title);
        i.putExtra("content",content);
        PendingIntent pi= PendingIntent.getService(ChildForgetActivity.this,(int)time,i,0);//编号time
        manager.set(AlarmManager.RTC_WAKEUP,time,pi);
    }
    public void cancelAlert(long time){
        Toast.makeText(ChildForgetActivity.this,"删除闹钟",Toast.LENGTH_SHORT).show();
        Intent i = new Intent(ChildForgetActivity.this,AlarmService.class);
        PendingIntent pi= PendingIntent.getService(ChildForgetActivity.this,(int)time,i,0);//编号time
        manager.cancel(pi);
    }
}
